package dict_list_controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	dld "pear-admin-layui-go/app/sys/dict_list/domain"
	dls "pear-admin-layui-go/app/sys/dict_list/service"
	"pear-admin-layui-go/framework/login_filter"
	fr "pear-admin-layui-go/framework/result"
	ft "pear-admin-layui-go/framework/table"
	"strconv"
	"time"
)

func Enable(c *gin.Context) {
	var dler dld.DictListEnableRequest
	_ = c.ShouldBind(&dler)
	user, _ := login_filter.GetCurrentUser(c)
	dler.UpdateBy = user.Id
	dler.UpdateName = user.Username
	dler.UpdateTime = time.Now().Unix()
	db := dls.Enable(&dler)
	fr.Result(c, db)
}

func IsDefault(c *gin.Context) {
	var dler dld.DictIsDefaultEnableRequest
	_ = c.ShouldBind(&dler)
	user, _ := login_filter.GetCurrentUser(c)
	dler.UpdateBy = user.Id
	dler.UpdateName = user.Username
	dler.UpdateTime = time.Now().Unix()
	db := dls.IsDefault(&dler)
	fr.Result(c, db)
}

func EditPage(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	dl := dls.EditPage(id)
	c.HTML(http.StatusOK, "sys/dict_list/edit.html", gin.H{
		"id":        dl.Id,
		"dataLabel": dl.DataLabel,
		"dataValue": dl.DataValue,
		"remark":    dl.Remark,
	})
}

func AddPage(c *gin.Context) {
	typeCode := c.Param("typeCode")
	c.HTML(http.StatusOK, "sys/dict_list/add.html", gin.H{
		"typeCode": typeCode,
	})
}

func Edit(c *gin.Context) {
	var dler dld.DictListEditRequest
	_ = c.ShouldBind(&dler)
	user, _ := login_filter.GetCurrentUser(c)
	dler.UpdateTime = time.Now().Unix()
	dler.UpdateBy = user.Id
	dler.UpdateName = user.Username
	db := dls.Edit(&dler)
	fr.Result(c, db)
}

func Save(c *gin.Context) {
	var dlsr dld.DictListSaveRequest
	_ = c.ShouldBind(&dlsr)
	user, _ := login_filter.GetCurrentUser(c)
	dlsr.CreateName = user.Username
	dlsr.CreateBy = user.Id
	dlsr.CreateTime = time.Now().Unix()
	_, err := dls.Save(&dlsr)
	fr.Result(c, err)
}

func Table(c *gin.Context) {
	var dlst dld.DictListSearchTable
	_ = c.ShouldBind(&dlst)
	table, count := dls.Table(&dlst)
	dlTable := make([]dld.DictListTableResponse, len(table))
	for i, v := range table {
		dlTable[i] = dld.DictListTableResponse{
			Id:         v.Id,
			TypeCode:   v.TypeCode,
			DataLabel:  v.DataLabel,
			DataValue:  v.DataValue,
			IsDefault:  v.IsDefault,
			Enable:     v.Enable,
			CreateTime: v.CreateTime,
			CreateName: v.CreateName,
			UpdateTime: v.UpdateTime,
			UpdateName: v.UpdateName,
			Remark:     v.Remark,
		}
	}
	c.JSON(http.StatusOK, ft.TableResponse{
		Data:  dlTable,
		Count: count,
	})
}
